package com.vr.xxaiagent.app;

import com.vr.xxaiagent.advisor.MyLoggerAdvisor;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 恋爱app
 *
 * @author hzh
 * @date 2025/06/01
 */
@Slf4j
@Component
public class LoveApp {
    private final ChatClient chatClient;
    private static final String SYSTEM_PROMPT = "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。" +
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。" +
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";


    private static final String CHAT_MEMORY_CONVERSATION_ID_KEY = "chat_memory_conversation_id";
    private static final String CHAT_MEMORY_RESPONSE_SIZE_KEY = "chat_memory_response_size";

    @Resource
    private ToolCallback[] allTools;

    @Resource
    private VectorStore loveAppVectorStore;
    @Resource
    private Advisor loveAppRagCloudAdvisor;
    // @Resource
    // private VectorStore pgVectorVectorStore;
    /*
     * 会自动注入mcp的工具
     * */
    @Resource
    private ToolCallbackProvider toolCallbackProvider;
    // 默认的会话记忆,基于内存
    private static final ChatMemory CHAT_MEMORY = new InMemoryChatMemory();


    public LoveApp(ChatModel dashscopeChatModel) {
        // 初始化基于内存的会话记忆
        // ChatMemory chatMemory = new InMemoryChatMemory();
        // 基于文件的会话记忆
        // String fileDir = System.getProperty("user.dir") + "/chat_memory";
        // ChatMemory fileBaseChatMemory = new FileBaseChatMemory(fileDir);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                // 拦截器
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(CHAT_MEMORY),
                        // 自定义日志，按需开启
                        new MyLoggerAdvisor()
                        // 自定义增强advisor，按需引入
                        // new ReReadingAdvisor()
                )
                .build();
    }

    public String doChat(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }


    record LoveReport(String title, List<String> suggestions) {
    }

    /**
     * 以指定结构的方式输出报告
     */
    public LoveReport doChatWithReport(String message, String chatId) {
        LoveReport loveReport = chatClient.prompt()
                // 系统提示词，会覆盖默认的,需要具体的提示词，才能更好的结构化输出
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                .call()
                .entity(LoveReport.class);
        log.info("loveReport:{}", loveReport);
        return loveReport;
    }

    /**
     * 用rag的方式聊天
     */
    public String doChatWithRag(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                // 应用本地知识库文档(就是将通过用户的message获取相关文档切片列表，拼接到prompt里)
                // .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                // 使用云端的知识库
                .advisors(loveAppRagCloudAdvisor)
                // 使用pgVector作为矢量数据库文档
                // .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }

    public String doChatWithTools(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                .tools(allTools)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }

    public String doChatWithMap(String message, String chatId) {
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                .tools(toolCallbackProvider)
                .call()
                .chatResponse();
        String content = chatResponse.getResult().getOutput().getText();
        log.info("content:{}", content);
        return content;
    }

    public Flux<String> doChatByStream(String message, String chatId) {
        return chatClient.prompt()
                .user(message)
                .advisors(advisorSpec -> advisorSpec
                        // 会话id
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        // 会话历史记录条数
                        .param(CHAT_MEMORY_RESPONSE_SIZE_KEY, 100))
                .tools(toolCallbackProvider)
                // 以流的方式输出
                .stream()
                .content();
    }

    /**
     * 获取消息列表
     *
     * @param chatId 会话id
     * @return {@code List<String> }
     */
    public Map<String, List<String>> getMessageList(String chatId) {
        List<Message> messages = CHAT_MEMORY.get(chatId, 10);
        // key:  提示词类型，value: 对应地会话内容列表
        return messages.stream()
                // 按照提示词地类型分组
                .collect(Collectors.groupingBy(message -> message.getMessageType().getValue(),
                        Collectors.mapping(Message::getText, Collectors.toList())));
    }

}
